package com.mtw.bbs.common.web.interceptor;


import com.alibaba.fastjson.JSON;
import com.mtw.bbs.common.core.constant.AuthConstant;
import com.mtw.bbs.common.core.security.context.SecurityContext;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;



/**
 * 基础Feign配置请求的token
 */
@Slf4j
public class BaseFeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(requestAttributes != null){
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            String authed = request.getHeader(AuthConstant.SERVICE_AUTH_KEY);
            SecurityContext context = SecurityContextHolder.getContext();
            template.header(AuthConstant.SERVICE_AUTH_KEY, authed);
            template.header(AuthConstant.AUTH_USER_KEY, JSON.toJSONString(context.getAuthentication()));
        }
    }
}
